<template>
	<view class="footer" :class="{ 'footer-bottom': top == 0 }" :style="{bottom: top+'px'}" @tap.stop="">
		<view class="footer-top" :style="{height: footerHeight + 'rpx'}">
			<!-- 	<view class="voice">
				<image v-if="showaudio" @click="binaudio" class="pub-icon" mode="aspectFill"
					src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/audio.png"></image>
				键盘
				<image v-else class="pub-icon" @click="binaudio" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/keyboard.png">
				</image>
			</view> -->
			<!-- 回话框 -->
			<view class="textarea-view" v-if="showaudio">
				<textarea @blur="blurChanginput" @focus="changinput" confirm-hold :always-embed="true"
					@confirm="sendTextMessage" v-model="inputText" :adjust-position="false" confirm-type="send"
					class="textarea" placeholder="请输入你想说的话" auto-height @linechange="linechange" />
			</view>
			<!-- <input @blur="blurChanginput" @focus="changinput" confirm-hold cursor-spacing="10" :always-embed="true"
				@confirm="sendTextMessage" v-model="inputText" v-if="showaudio" :adjust-position="false"
				confirm-type="send" class="textarea" auto-height maxlength="-1" placeholder="请输入你想说的话"></input> -->

			<!-- 语音框 -->
			<button @longpress="handleLongPress" @touchmove="handleTouchMove" @touchend="handleTouchEnd" v-else
				class="audio" color="#f8f8f8">{{ audioText }}</button>

			<view class="voice voice1">
				<view @tap="binEmoji" class="dy-iconfont icon-xingzhuangjiehebeifen"></view>
				<!-- <image @click="binEmoji" class="pub-icon" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/xiaol.png"></image> -->
			</view>
			<view class="voice" @tap="addTap">
				<view class="dy-iconfont icon-a-xingzhuangjiehebeifen2"></view>
				<!-- <image @click="binEmoji" class="pub-icon" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/xiaol.png"></image> -->
			</view>
			<!-- 发送按钮 -->
			<!-- <view class="send-btn" v-if="inputText">
				<button @click="sendTextMessage" class="send-btn-button">发送</button>
			</view> -->
		</view>
		<!-- 表情 -->
		<view v-show="modeStr === 'emoji'" class="emoji">
			<TUI-Emoji @enterEmoji="appendMessage" :show="modeStr"></TUI-Emoji>
		</view>
		<!-- 按钮 -->
		<view class="btn-list-box" :class="{ 'btn-list-muneList': modeStr === 'list' }">
			<view class="btn-list">
				<!-- <view class="btn-li">
					<image class="btn-icon" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/yuy.png"></image>
				</view> -->
				<view class="btn-li">
					<view @click="handleSendImage" class="dy-iconfont icon-tupian"></view>
					<view class="title">照片</view>
					<!-- <image @click="handleSendImage" class="btn-icon" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/zp.png"></image> -->
				</view>
				<view class="btn-li">
					<view @click="handleSendPicture" class="dy-iconfont icon-paishe"></view>
					<view class="title">拍摄</view>
					<!-- <image class="btn-icon" @click="handleSendPicture" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/xj.png"></image> -->
				</view>
				<!-- <view class="btn-li">
					<image class="btn-icon" mode="aspectFill" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/img/sp.png"></image>
				</view> -->
			</view>
		</view>
		<!-- 录音状态 -->
		<view class="record-modal" v-if="popupToggle" @longpress="handleLongPress" @touchmove="handleTouchMove"
			@touchend="handleTouchEnd">
			<!-- <u--text color="#fff" align="center" size="30rpx" :text="title"></u--text> -->
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import TUIEmoji from '../message-elements/emoji/index';
	import {
		mapState
	} from "vuex";
	const app = getApp();
	export default {
		components: {
			TUIEmoji,
		},
		options: {
			styleIsolation: 'shared'
		}, //解决/deep/不生效**
		props: ['conversation', "clearfootersModeFlag", "scorllTransitionFasle"],
		data() {
			return {
				firstSendMessage: true,
				modeStr: "",
				showaudio: true,
				inputText: '',
				btnStyle: {
					height: '60rpx'
				},
				top: 0,
				title: '说话中',
				popupToggle: false,
				recorderManager: '',
				recordTimer: null,
				canSend: true,
				isRecording: false,
				footHeader: false,
				startPoint: 0,
				recordTime: 0,
				audioText: '按住说话',
				footerHeight: 140,
				changeheight: 0,
				lineCount: 1,
				rpx: app.globalData.widthPx / 750,
				lineHeight: 0
			}
		},
		watch: {
			modeStr: {
				handler(nval, oval) {
					this.$emit("scorllTransitionFasle");
					this.$nextTick(() => {
						if (nval) {
							if (nval === 'list') {
								this.$emit('changinput', {
									height: 240,
									type: 1

								});
							} else if (nval === 'input') {
								this.$emit('changinput', {
									height: this.top / this.$store.state.rpxSize,
									type: 1

								});
							} else {
								this.$emit('changinput', {
									height: 480,
									type: 1
								});
							}
						} else {
							this.$emit('changinput', {
								height: 0,
								type: 1
							});

						}

					})

				},
				immediate: true
			},
			footHeader: {
				handler(nval, oval) {
					// this.$nextTick(() => {
					// 	this.$emit('changinput', {
					// 		height: nval ? 80 : 0,
					// 		type: 1
					// 	});
					// })
				},
				immediate: true
			},
			footerHeight: {
				handler(nval, oval) {
					this.$emit('changeheight', nval);
				},
				immediate: true
			},
			clearfootersModeFlag: {
				handler(nval, oval) {
					if (this.modeStr != "") {
						this.modeStr = "";
					}
				},
			}


		},
		computed: {
			...mapState({
				isSDKReady: state => state.isSDKReady,
			}),
			footHeaderHeight() {
				if (this.footHeader) {
					return 80
				} else {
					return 0
				}
			},
		},
		created() {
			let footHeader = uni.getStorageSync('footHeader') ? uni.getStorageSync('footHeader') : false
			this.footHeader = footHeader;
			if (footHeader) {
				this.modeStr = false;
			}
		},
		mounted() {
			// 加载声音录制管理器
			this.recorderManager = uni.getRecorderManager();
			this.recorderManager.onStop(res => {
				clearInterval(this.recordTimer);
				// 兼容 uniapp 打包app，duration 和 fileSize 需要用户自己补充
				// 文件大小 ＝ (音频码率) x 时间长度(单位:秒) / 8
				let msg = {
					duration: res.duration ? res.duration : this.recordTime * 1000,
					tempFilePath: res.tempFilePath,
					fileSize: res.fileSize ? res.fileSize : ((48 * this.recordTime) / 8) * 1024
				};
				uni.hideLoading();
				// 兼容 uniapp 语音消息没有duration
				if (this.canSend) {
					if (msg.duration < 1000) {
						uni.showToast({
							title: '录音时间太短',
							icon: 'none'
						});
					} else {
						// res.tempFilePath 存储录音文件的临时路径
						const message = uni.$TUIKit.createAudioMessage({
							to: this.getToAccount(),
							conversationType: this.conversation.type,
							payload: {
								file: msg
							},
							needReadReceipt: true
						})
						this.$sendTIMMessage(message);
					}
				}
				this.startPoint = 0
				this.popupToggle = false
				this.isRecording = false
				this.canSend = true
				this.title = " "
				this.audioText = "按住说话"
			})
		},
		methods: {
			addTap() {
				if (this.modeStr === 'list') {
					this.modeStr = "";
				} else {
					this.modeStr = "list";
				}
				uni.hideKeyboard()
			},
			// 表情显示隐藏
			binEmoji() {
				if (this.modeStr === 'emoji') {
					this.modeStr = "";
				} else {
					this.modeStr = "emoji";
				}
				uni.hideKeyboard()
			},
			isFootHeader() {
				this.$handleSendCustomMessage()
			},
			$handleSendCustomMessage(e) {
				const message = uni.$TUIKit.createCustomMessage({
					to: this.getToAccount(),
					conversationType: this.conversation.type,
					payload: {
						data: 'telephone',
						description: '电话通知',
					}
				});
				this.$sendTIMMessage(message, 'custom');
			},
			// 输入框
			changinput(e) {
				// console.log(e.detail);
				this.top = e.detail.height
				if (this.modeStr === 'input') {
					this.modeStr = "";
				} else {
					this.modeStr = "input";
				}

			},
			linechange(e) {
				this.lineHeight = e.detail.height / e.detail.lineCount / this.rpx
				if (e.detail.lineCount == 1) {
					this.footerHeight = 140
				} else if (e.detail.lineCount > this.lineCount) {
					if (e.detail.lineCount < 5) {
						this.footerHeight = this.footerHeight + this.lineHeight
					}else{
						this.footerHeight = this.footerHeight > 200 ? this.footerHeight : 140 + this.lineHeight * 3
					}
				} else {
					if (e.detail.lineCount < 5) {
						this.footerHeight = this.footerHeight - this.lineHeight
					}
				}
				this.lineCount = e.detail.lineCount
			},
			touchstartBottom() {
				this.modeStr = "";
			},
			blurChanginput(e) {
				this.top = 0
				if (this.modeStr != "input") {
					return
				}
				this.modeStr = "";

			},
			// 表情
			appendMessage(e) {
				this.inputText = this.inputText + e.detail.message
			},
			// 拍照
			handleSendPicture() {
				this.sendImageMessage('camera');
			},
			// 上传图片
			handleSendImage() {
				this.sendImageMessage('album');
			},
			// 上传封装
			sendImageMessage(type) {
				uni.chooseImage({
					sourceType: [type],
					count: 1,
					success: res => {
						if (res) {
							setTimeout(() => {
								const message = uni.$TUIKit.createImageMessage({
									to: this.getToAccount(),
									conversationType: this.conversation.type,
									payload: {
										file: res
									},
									needReadReceipt: true,
									onProgress: percent => {
										message.percent = percent;
									}
								});
								this.muneList = false
								this.$sendTIMMessage(message, 'image');
							}, 500)
						}
					}
				});
			},
			// 手指离开页面滑动
			handleTouchEnd() {
				this.isRecording = false
				this.popupToggle = false
				uni.hideLoading();
				this.recorderManager.stop();
			},
			// 录音
			handleLongPress(e) {
				this.recorderManager.start({
					duration: 60000,
					// 录音的时长，单位 ms，最大值 600000（10 分钟）
					sampleRate: 44100,
					// 采样率
					numberOfChannels: 1,
					// 录音通道数
					encodeBitRate: 192000,
					// 编码码率
					format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
				});
				this.startPoint = e.touches[0]
				this.title = '正在录音'
				this.popupToggle = true
				this.isRecording = true
				this.recordTime = 0
				this.recordTimer = setInterval(() => {
					this.recordTime++;
				}, 1000)
			},
			// 录音时的手势上划移动距离对应文案变化
			handleTouchMove(e) {
				if (this.isRecording) {
					if (this.startPoint.screenY - e.touches[e.touches.length - 1].screenY > 100) {
						this.audioText = "抬起停止"
						this.title = "松开手指，取消发送"
						this.canSend = false
					} else if (this.startPoint.screenY - e.touches[e.touches.length - 1].screenY > 20) {
						this.audioText = "抬起停止"
						this.title = "上划可取消"
						this.canSend = true
					} else {
						this.audioText = "抬起停止"
						this.title = "正在录音"
						this.canSend = true
					}
				}
			},
			// 语音
			binaudio() {
				this.showaudio = !this.showaudio
			},
			/**
			 * 发送消息校验
			 * @param {*} messages 
			 */
			validMessages(str) {
				// 匹配规则：任意字符 不能为空
				var re = /\S/
				return re.test(str)
			},

			// 发送
			sendTextMessage(msg, flag) {
				const to = this.getToAccount();
				const text = flag ? msg : this.inputText;
				if (text == '夏目又高又帅') {
					this.inputText = ''
					app.navigationTo('page_account/setting/operational')
					return
				}
				if (!this.validMessages(text)) {
					this.$refs.toast.show({
						type: 'default',
						message: "请输入消息内容"
					})
					setTimeout(() => {
						this.$refs.toast.hide()
					}, 1000)
					return
				}
				const message = uni.$TUIKit.createTextMessage({
					to,
					conversationType: this.conversation.type,
					payload: {
						text
					},
					needReadReceipt: true
				});
				this.inputText = "";
				this.$sendTIMMessage(message, 'text');
			},
			// 发送到IM
			$sendTIMMessage(message, type) {
				const SDKAppID = getApp().globalData.SDKAppID;

				uni.$TUIKit.sendMessage(message).then((res) => {
					this.$emit('sendMessage', {
						detail: {
							message,
							type
						}
					});
					if (type != 'custom') {
						this.getUserStatus(message, type)
					}
					if (this.firstSendMessage) {
						// uni.$aegis.reportEvent({
						// 	name: 'sendMessage',
						// 	ext1: 'sendMessage-success',
						// 	ext2: 'uniTuikitExternal',
						// 	ext3: `${SDKAppID}`,
						// })
					}
					this.firstSendMessage = false
				}).catch((error) => {
					this.$emit("sendError")
				})
			},
			// 获取用户状态
			getUserStatus(message, type) {
				let msg = type == 'image' ? '图片' : message._elements[0].content.text
				let toUserId = this.conversation.conversationID.split('C2C')[1]
				app._post_form(
					"/client/im/sendMessage", {
						messageContent: msg,
						toUserId: toUserId
					},
					(result) => {}
				);
			},
			// 获取用户
			getToAccount() {
				if (!this.conversation || !this.conversation.conversationID) {
					return '';
				}
				switch (this.conversation.type) {
					case 'C2C':
						return this.conversation.conversationID.replace('C2C', '');

					case 'GROUP':
						return this.conversation.conversationID.replace('GROUP', '');

					default:
						return this.conversation.conversationID;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.reminder {
		padding-top: 140rpx;
	}

	.signPop {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;

		.btn-primary {
			text-align: center;
			font-size: 26rpx;
			flex-shrink: 0;
			width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
		}

		.btn-custom {
			border: 2rpx solid #7B867F;
			color: #999B9B;
			background: #FFFFFF;
		}
	}

	.record-modal {
		position: fixed;
		left: 225rpx;
		bottom: 500rpx;
		width: 280rpx;
		@include flex(row);
		align-items: center;
		justify-content: center;
		height: 280rpx;
		border-radius: 20rpx;
		background-color: rgba(0, 0, 0, 0.6);
	}

	.footer-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

	}

	.footer {
		width: 100vw;
		box-sizing: border-box;
		background-color: #fff;
		// padding-bottom: var(--top);
		position: fixed;
		// bottom: var(--top);
		bottom: 0;
		z-index: 9999;
		// border: 1px solid blue;

		.send-btn {
			margin-right: 36rpx;

			.send-btn-button {
				width: 100px;
				height: 50rpx;
				background: linear-gradient(144deg, #CCFA2F 0%, #ABF61A 55%, #A7F517 100%);
				border-radius: 40px;
				font-size: 26rpx;
				font-weight: 900;
				color: #1E1F1F;
				line-height: 50rpx;
			}
		}

		.often {
			margin: 20rpx 0;
			@include flex(row);
			align-items: center;

			.often-btn-bg {
				background-color: #FD9827;
				border-radius: 200rpx;
				padding: 10rpx 20rpx;
				margin-left: 20rpx;
			}
		}

		.audio {
			flex: 1;
			height: 80rpx;
			border-radius: 10rpx;
			font-size: 30rpx;
			border: none;
		}

		.foot-header {
			width: 100vw;
			height: 80rpx;
			background: #F6F8F7;
			box-sizing: border-box;
			padding: 20rpx 36rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-direction: row;

			.title {
				font-size: 26rpx;
				font-weight: 400;
				color: #999B9B;
			}

			.iphon {
				width: 130rpx;
				height: 50rpx;
				background: rgba(57, 109, 232, 0.05);
				border-radius: 25rpx;
				border: 1rpx solid #396DE8;
				font-size: 26rpx;
				font-weight: 900;
				color: #396DE8;
				line-height: 50rpx;
				text-align: center;
			}
		}

		.footer-top {
			@include flex(row);
			align-items: center;
			padding: 34rpx 0 42rpx 36rpx;
			box-sizing: border-box;
			border-top: 2rpx solid #E3E9E5;

			.textarea-view {
				background-color: #F6F8F7;
				min-height: 64rpx;
				max-height: 166rpx;
				// flex: 1;
				width: calc(100vw - 36rpx - 26rpx * 3 - 100rpx);
				border-radius: 36rpx;
				padding: 14rpx 20rpx;
			}


			.textarea {
				width: calc(100vw - 36rpx - 26rpx * 3 - 100rpx - 40rpx);
				position: relative;
				font-size: 28rpx;
			}

			.placeText {
				line-height: 64rpx;
			}

			.pub-icon {
				width: 52rpx;
				height: 52rpx;
				margin: 0 20rpx;
			}

			.voice {
				padding: 0 26rpx;

				&.voice1 {
					padding-right: 0;
				}

				.dy-iconfont {
					font-size: 46rpx;
					color: #282D2D;
				}
			}
		}
	}

	.btn-list-box {
		background-color: #F6F8F7;
		border-top: 2rpx solid #E3E9E5;
		display: none;
		height: 0;
		transition: all .2s;
		box-sizing: border-box;

		&.btn-list-muneList {
			height: 240rpx;
			display: block;
			transition: all .2s;
		}
	}

	.btn-list {
		@include flex(row);
		align-items: center;
		padding: 20rpx 48rpx;

		.btn-li {
			// flex: 1;
			@include flex(row);
			align-items: center;
			flex-direction: column;
			margin: 0 24rpx 0 0;

			.dy-iconfont {
				text-align: center;
				@include flex(row);
				align-items: center;
				justify-content: center;
				font-size: 54rpx;
				width: 140rpx;
				height: 140rpx;
				background: #FFFFFF;
				border-radius: 40rpx;
			}

			.title {
				font-size: 26rpx;
				font-weight: 400;
				color: #222222;
				line-height: 37rpx;
				margin-top: 16rpx;
			}
		}
	}
</style>